package com.bw.dg.controller;

import com.bw.dg.util.FileUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @ProjectName: shouqiuroject
 * @Package: com.bw.shouqiu.controller
 * @ClassName: fileController
 * @Author: 社会佩奇
 * @Description: fileController
 * @Date: 2020/4/1 9:34
 * @Version: 1.0
 */
@Controller
@CrossOrigin
@RequestMapping("file")
public class FileController {

    private final ResourceLoader resourceLoader;

    @Autowired
    public FileController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @PostMapping("upload")
    @ResponseBody
    public String fileload(MultipartFile file){
        Map<String, String> map = FileUtil.fileUpload(file);
        String fileName = map.get("fileName");
        return fileName;
    }
    @RequestMapping(value = "/showImage")
    public ResponseEntity showImage(String imgPath, HttpServletResponse response) throws IOException {
        imgPath = StringUtils.isNotEmpty(imgPath) ? ("file:"+FileUtil.uploadPath()+imgPath) : "uploadImg.jpg";
        System.out.println(imgPath);
        return ResponseEntity.ok(resourceLoader.getResource(imgPath));
    }
    /*@RequestMapping(value = "/showImage")
    @ResponseBody
    public void showImage(String imgPath, HttpServletResponse response) throws IOException {
        imgPath = StringUtils.isNotEmpty(imgPath) ? imgPath : "uploadImg.jpg";
        File file = new File(imgPath);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        response.setContentType("image/jpeg");
        OutputStream out = response.getOutputStream();
        out.write(bytes);
        out.flush();
        //关闭响应输出流
        out.close();
    }*/
    /*@RequestMapping(value = "/showImage")
    @ResponseBody
    public byte[] showImage(String imgPath) throws IOException {
        imgPath = StringUtils.isNotEmpty(imgPath) ? imgPath : "uploadImg.jpg";
        File file = new File(FileUtil.uploadPath()+imgPath);
        FileInputStream inputStream = new FileInputStream(file);
        byte[] bytes = new byte[inputStream.available()];
        inputStream.read(bytes, 0, inputStream.available());
        return bytes;
    }*/


}
